<template>
  <div>
    <div class="goodimg">
      <img :src="good.goodImgUrl" alt="图片丢失了" />
    </div>

    <div class="goodinfo">
      <h3>商品名称:{{good.goodName}}</h3>
      <h3>商品简介:{{good.goodInfo}}</h3>
      <h3>销量:{{good.goodSell}}</h3>
      <h3>价格:{{good.goodNowPrice}}</h3>

      <div v-if="isSecKill">
        <h3>秒杀价:{{good.goodSecKillPrice}}</h3>
        <h3>秒杀开始时间:{{good.startTime}}</h3>
        <h3>秒杀结束时间:{{good.endTime}}</h3>
      </div>

      <el-button type="primary" @click="addCart">加入购物车</el-button>
      <el-button
        type="primary"
        @click="choseAddress"
        :disabled="isEnableSecKill"
        v-if="isSecKill"
      >立即秒杀</el-button>
    </div>

    <!-- 商品评论 -->
    <div class="goodcomment">
      <div>
        商品评论:
        <el-radio-group v-model="star">
          <el-radio :label="null">全部评论</el-radio>
          <el-radio :label="5">好评</el-radio>
          <el-radio :label="3">中评</el-radio>
          <el-radio :label="1">差评</el-radio>
        </el-radio-group>
        <div class="textcontent">
          <el-input
            id="input"
            type="textarea"
            v-model="replyParams.replyContent"
            :placeholder="placeholder"
            ref="commenttext"
            @keyup.enter.native="addreply"
            v-show="inputVisible"
          ></el-input>
        </div>
      </div>

      <!-- 遍历实体 -->
      <div>
        <div class="usercomment" v-for="item in comment" :key="item.commentId">
          <div class="user">
            <div class="userleft">
              <el-row :gutter="20">
                <el-col :span="17">
                  <el-avatar :src="item.userImgUrl"></el-avatar>
                  <p>{{item.userName}}</p>
                  评论时间:{{item.commentTime}}
                  <el-rate v-model="item.star" disabled></el-rate>
                </el-col>
                <el-col :span="4">
                  <p>{{item.commentContent}}</p>
                  <el-button type="primary" @click="showText(item.commentId,item.userName)">评论</el-button>
                </el-col>
              </el-row>
            </div>
          </div>

          <!-- 回复内容 -->
          <div v-for="reply in item.replyVoList" :key="reply.Id">
            <el-row :gutter="20">
              <el-col :span="11">
                <div class="replyleft">
                  <el-avatar :src="reply.userImgUrl"></el-avatar>
                  <span>{{reply.userName}} ":"{{reply.replyComment}}</span>
                </div>
              </el-col>
              <span>
                {{reply.replyTime}}
                <el-button type @click="showText2(reply.replyId,reply.userId,reply.userName)">回复</el-button>
              </span>
            </el-row>

            <div v-for="bereply in reply.replyVos" :key="bereply.id">
              <el-row :gutter="20">
                <el-col :span="11">
                  <div class="replyleft">
                    <el-avatar :src="bereply.replyUserImgUrl"></el-avatar>
                    <span>{{bereply.replyUserName}}"回复"</span>
                    <span>{{bereply.beReplyUserName}}":"</span>
                    <span>{{bereply.replyContent}}</span>
                  </div>
                </el-col>
                <span>
                  {{bereply.replyTime}}
                  <el-button
                    type
                    @click="showText2(reply.replyId,bereply.userId,bereply.replyUserName)"
                  >回复</el-button>
                </span>
              </el-row>

              <div class="userright"></div>
            </div>
          </div>
        </div>
      </div>
      <!-- 分页 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :page-count="100"
        :current-page="commentParams.currentPage"
        :page-size="10"
        @current-change="getPage"
      ></el-pagination>
    </div>

    <el-dialog title="选择地址" :visible.sync="dialogVisible" width="30%">
      <div>
        <el-table
          ref="singleTable"
          :data="addressLists"
          highlight-current-row
          @current-change="handleCurrentChange"
          style="width: 100%"
        >
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column property="userName" label="收件人" width="120" prop="userName"></el-table-column>
          <el-table-column property="userPhone" label="电话" width="120" prop="userPhone"></el-table-column>
          <el-table-column property="userAddress" label="地址" prop="userAddress"></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitOrder">立刻抢购</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getGoodDetail,
  addGoodCart,
  getUserAddress,
  SecKillGood,
  getGoodComment,
  addReply,
} from "../api/requestapi";
import { get } from "../api/axios";
export default {
  name: "GoodDetail",

  data() {
    return {
      //商品信息
      good: {
        goodId: "",
        goodName: "",
        goodNowPrice: "",
        goodSell: "",
        goodInfo: "",
        goodImgUrl: "",
        goodStatus: "",
        goodSecKillPrice: "",
        startTime: "",
        endTime: "",
      },

      //评论信息
      comment: [],

      //控制秒杀信息的显示
      isSecKill: false,

      //是否可以点击秒杀按钮
      isEnableSecKill: false,

      //用户地址显示
      dialogVisible: false,

      //用户地址信息
      addressLists: [],

      //
      star: "",

      inputVisible: false,

      placeholder: "请输入回复内容",

      //评论信息参数
      commentParams: {
        //当前商品id
        goodId: "",
        //评论星级 区分好评，差评中评
        star: "",
        //当前页数:''
        currentPage: 1,
        pageSize: 2,
      },

      //回复请求参数
      replyParams: {
        replyContent: "",
        repliedId: "",
        repliedUserId: "",
        commentId: "",
      },

      //秒杀请求参数
      seckillParams: {
        userName: "",
        userPhone: "",
        userAddress: "",
        goodId: "",
        goodSecKillPrice: "",
      },

      //被选中地址信息
      userAddressInfo: {
        userName: "",
        userPhone: "",
        userAddress: "",
      },

      //秒杀请求参数
      orderParams: {
        goodId: [],
        userName: "",
        userPhone: "",
        userAddress: "",
        goodCount: [],
        total: "",
      },
      websocket: {
        path: "ws://localhost:8889/api/websocket/100",
      },
    };
  },

  methods: {
    //添加购物车
    addCart() {
      addGoodCart(this.good.goodId).then();
    },
    // 抢购接口
    commitOrder() {
      //设置选择的地址
      this.seckillParams.userName = this.userAddressInfo.userName;
      this.seckillParams.userPhone = this.userAddressInfo.userPhone;
      this.seckillParams.userAddress = this.userAddressInfo.userAddress;
      SecKillGood(this.seckillParams).then((res) => {});
    },

    //显示评论框
    showText(commentid, name) {
      //清空参数
      this.replyParams = {};
      this.replyParams.commentId = commentid;
      this.placeholder = "回复:" + name + "(按回车进行评论)";
      //光标移动
      var input = document.getElementById("input");
      this.inputVisible = true;
      input.focus();
    },
    showText2(replyId, userid, name) {
      //清空参数
      this.replyParams = {};
      this.replyParams.repliedId = replyId;
      this.replyParams.repliedUserId = userid;
      this.placeholder = "回复:" + name + "(按回车进行评论)";
      //光标移动
      var input = document.getElementById("input");
      this.inputVisible = true;
      input.focus();
    },

    //添加一条评论
    addreply() {
      addReply(this.replyParams).then((res) => {
        if (res.code == 200) {
          //清空参数
          this.replyParams = {};
          //改为不可见
          this.inputVisible = false;
        }
      });
    },

    //评论分页
    getPage(page) {
      console.log("进行分页" + page);
      this.commentParams.currentPage = page;
      getGoodComment(this.commentParams).then((res) => {
        console.log(res.data);
        this.comment = res.data;
      });
    },

    //选择用户地址
    choseAddress() {
      //判断有没有token(有没有登陆)
      var token = sessionStorage.getItem("token");
      if (token == null) {
        this.$router.push({ path: "/login" });
      }
      //获取数据
      getUserAddress().then((res) => {
        this.addressLists = res.data;
        this.dialogVisible = true;
      });
    },
    //设置选择的地址
    handleCurrentChange(val) {
      this.userAddressInfo.userAddress = val.userAddress;
      this.userAddressInfo.userPhone = val.userPhone;
      this.userAddressInfo.userName = val.userName;
    },

    //websokcet 初始化化
    init: function () {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.websocket.path);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
      }
    },
    open: function () {
      console.log("socket连接成功");
    },
    error: function () {
      console.log("连接错误");
    },
    //获得信息后回调函数
    getMessage: function (msg) {
      //把接受的json消息转化为 对象
      var object = JSON.parse(msg.data);
      //判断是不是购买本商品
      var goodIds = object.goodIds;

      console.log(goodIds);

      for (let item of goodIds) {
        console.log("人家购买的id" + item);
        console.log("该页面的商品id" + this.good.goodId);
        //假设当前id与当前id相等
        if (item == this.good.goodId) {
          this.$message({
            message: "用户" + object.userId + "购买了该商品",
            //显示5秒
            duration: 5 * 1000,
          });
        }
      }
    },
    send: function () {
      this.socket.send(this.text);
    },
    close: function () {
      console.log("socket已经关闭");
    },
    destroyed() {
      // 销毁监听
      this.socket.onclose = this.close;
    },
  },

  mounted() {
    this.init();
  },

  created() {
    //获取传过来的商品id
    var goodId = this.$route.query.goodId;

    //获取商品信息
    getGoodDetail(goodId).then((response) => {
      this.good = response.data;
      if (this.good.goodStatus == 2) {
        this.isSecKill = true;
        this.isEnableSecKill = !response.data.enableSecKill;
        this.seckillParams.goodId = goodId;
        this.seckillParams.goodSecKillPrice = this.good.goodSecKillPrice;
      }
    });

    this.commentParams.goodId = goodId;
    // 获取商品评论
    getGoodComment(this.commentParams).then((res) => {
      this.comment = res.data;
    });
  },

  watch: {
    star: {
      handler: function () {
        //初始化页面参数
        this.commentParams.currentPage = 1;
        this.commentParams.pageSize = 10;
        this.commentParams.star = this.star;
        getGoodComment(this.commentParams).then((res) => {
          this.comment = res.data;
        });
      },

      // deep: true,
    },
  },
};
</script>

<style>
body {
  height: 100%;
}
.goodimg {
  width: 500px;
  height: 500px;
  margin-right: 30px;
  position: absolute;
  top: 300px;
  left: 50px;
}
.goodimg img {
  width: 300px;
  height: 300px;
}

.goodinfo {
  position: absolute;
  top: 300px;
  right: 700px;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

.goodcomment {
  width: 2000px;
  position: absolute;
  font-size: 10px;
  left: -300px;
  margin: 0 auto;
  top: 700px;
}
.usercomment {
  width: 1300px;
  margin-left: auto;
  margin-right: auto;
  /* 添加下划线 */
  border-bottom: 1px solid;
}
.user {
  margin-top: 30px;
  height: 150px;
  padding: 0;
}
.userleft {
  /* width: 300px;
  position: relative;
  left: 30px; */
  /* width: 200px; */
}
.user .userright {
  width: 300px;
  float: right;
}

.replyleft {
  margin-left: 300px;
}

.textcontent {
  width: 500px;
  margin: 0 auto;
}
</style>